// 上传图片

import SendUrl from './config.js'
const config = SendUrl.AllUrl

export function UpdataImg(file, callback) {
	var that = this
	var ImgArr = []
	uni.showLoading({
		title: '上传中...',
	})
	for (var i in file) {
		UpImgResolve(file[i], i).then((res) => {
			ImgArr.push(res)
			uni.hideLoading();
			console.log('res111', res)
			// 当需要上传的文件上传完，返回上传成功的数组
			if (ImgArr.length == file.length) {
				callback(ImgArr)
				uni.hideLoading();
			}

		})
	}
}

export function UpImgResolve(file, index) {
	return new Promise(function(resolve, reject) {
		uni.uploadFile({
			url: config + "/upload/save-img",
			filePath: file,
			name: 'file',
			formData: {
				'user': "test"
			},
			success: function(uploadFileRes) {
				console.log('uploadFileRes', uploadFileRes)
				// var date ={
				// 	index:index,
				// 	img:JSON.parse(uploadFileRes.data)
				// }
				resolve(uploadFileRes.data)
			},
			error(res) {
				uni.hideLoading();
			}
		});
	})
}
// 封装获取到全局数据 -- 类型
export function GetType(type) {
	if (type == 1) {
		return new Promise(function(resolve, reject) {
			uni.request({
				url: config + "/electric/model/page",
				data: {},
				method: "GET",
				dataType: 'json',
				header: {
					'content-type': 'application/json;charset=UTF-8',
					"Authorization": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					if (res.data.code == 200) {
						resolve(res);
					} else {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
						reject(res.data.msg);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err)
				}
			})
		})
	} else {
		return new Promise(function(resolve, reject) {
			uni.request({
				url: config + "/battery/classify",
				data: {},
				method: "GET",
				dataType: 'json',
				header: {
					'content-type': 'application/json;charset=UTF-8',
					"Authorization": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					if (res.data.code == 200) {
						resolve(res);
					} else {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
						reject(res.data.msg);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err)
				}
			})
		})
	}

}
// --- 获取品牌 /electric/brand/page
export function GetBrand(Type) {
	if (Type == 1) {
		return new Promise(function(resolve, reject) {
			uni.request({
				url: config + "/electric/brand/page",
				data: {},
				method: "GET",
				dataType: 'json',
				header: {
					'content-type': 'application/json;charset=UTF-8',
					"Authorization": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					if (res.data.code == 200) {
						resolve(res);
					} else {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
						reject(res.data.msg);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err)
				}
			})


		})
	} else {
		return new Promise(function(resolve, reject) {
			uni.request({
				url: config + "/battery/brand",
				data: {},
				method: "GET",
				dataType: 'json',
				header: {
					'content-type': 'application/json;charset=UTF-8',
					"Authorization": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					if (res.data.code == 200) {
						resolve(res);
					} else {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
						reject(res.data.msg);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err)
				}
			})


		})
	}

}
// --- 获取型号
export function GetModel(Type) {
	if (Type == 1) {
		return new Promise(function(resolve, reject) {
			uni.request({
				url: config + "/electric/model/page",
				data: {},
				method: "GET",
				dataType: 'json',
				header: {
					'content-type': 'application/json;charset=UTF-8',
					"Authorization": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					if (res.data.code == 200) {
						resolve(res);
					} else {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
						reject(res.data.msg);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err)
				}
			})
		})
	} else {
		return new Promise(function(resolve, reject) {
			uni.request({
				url: config + "/battery/battery/model",
				data: {},
				method: "GET",
				dataType: 'json',
				header: {
					'content-type': 'application/json;charset=UTF-8',
					"Authorization": uni.getStorageSync("token") || ''
				},
				success: (res) => {
					if (res.data.code == 200) {
						resolve(res);
					} else {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
						reject(res.data.msg);
					}
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err)
				}
			})


		})
	}

}
// 扫码入口
export function scanCode(callback) {
	uni.scanCode({
		success: function(res) {
			callback(res.result)
		}
	});
}


// export function getLiveTimeCount(time,mins){
// 	   var date = ''
// 	   myTotaltime(time,mins,res=>{
// 	   		 date = res
// 	   })
// 	   setInterval(function(){
// 		   if(date != ''){
// 			   return date
// 		   }
// 	   },500)

// }


export function getLiveTimeCount(time, mins, callback) {
	if (time) { //如果设置了开始时间
		// 生成当前时间增加的分钟量
		var curTime = new Date(time);
		var liveCountdown = ''
		this.liveCountTimes = setInterval(() => {
			//注：不论安卓还是ios，请将时间如 2020-02-02 20:20:20 转化为 2020/02/02 20:20:20 这种形式后再使用，否则无法转换，如下转换即可↓
			// let transedPreTime=curTime.replace(/-/g,'/') //这里转化时间格式为以/分隔形式
			let nowTime = new Date().getTime();
			let preTime = new Date(curTime).getTime() + mins * 60 * 1000
			let obj = null;

			if (preTime - nowTime > 0) {
				let time = (preTime - nowTime) / 1000;
				let day = parseInt(time / (60 * 60 * 24));
				let hou = parseInt(time % (60 * 60 * 24) / 3600);
				let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
				let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
				obj = {
					day: day < 10 ? '0' + day : day,
					hou: hou < 10 ? '0' + hou : hou,
					min: min < 10 ? '0' + min : min,
					sec: sec < 10 ? '0' + sec : sec
				};
				liveCountdown = obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'

				callback(liveCountdown)

			} else {
				// obj = {day:'00',hou:'00',min:'00',sec:'00'};
				// liveCountdown=obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'
				liveCountdown = "已过期"
				callback(liveCountdown)
				clearInterval(this.liveCountTimes)
			}
		}, 1000)

	} else {
		liveCountdown = "已过期"
		callback(liveCountdown)
	}
}
// 判断数组对象是否用空值
export function judgeListComplete(list) {
	let isNotComplete = list.findIndex(item => {
		return judgeObjectComplete(item) === false
	})
	if (isNotComplete > -1) {
		return false
	} else {
		return true
	}
}

export function judgeObjectComplete(ObjectValue) {
	let flag = new Boolean()
	flag = true
	for (let key in ObjectValue) {
		if (ObjectValue[key] || ObjectValue[key] === 0) {} else {
			flag = false
		}
	}
	if (!flag) {
		return false
	} else {
		return true
	}
}

// 上传商品
export function Debounce(_this, callback) {
	if (_this.timeout !== null) clearTimeout(_this.timeout);
	_this.timeout = setTimeout(() => {
		callback(true)
	}, 400);
}
// 计算未读信息
export function compileNum(list, callback) {
	let unreadCount = 0
	if (list.length > 0) {
		for (var i in list) {
			unreadCount += list[i].unreadCount
			console.log('unreadCount', unreadCount)
		}
	}
	callback(unreadCount)

}

export function getPermissionSetting(permisionID, text, callback) {
	const app = getApp()
	if (uni.getStorageSync(permisionID) == '被永久拒绝权限' || uni.getStorageSync(permisionID) == '未获得授权') {
		uni.showModal({
			title: '提示',
			confirmText: '去授权',
			content: text,
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					app.gotoAppPermissionSetting()
					callback(false)
				} else if (res.cancel) {
					callback(false)
					console.log('用户点击取消');
				}
			}
		});

	} else {
		callback(true)
	}
}

export default {
	UpdataImg,
	GetType,
	GetBrand,
	scanCode,
	GetModel,
	getLiveTimeCount,
	judgeListComplete,
	Debounce,
	compileNum,
	getPermissionSetting
}
